package com.sgb.kjwl.view.ui.activity.self.websiteManage;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClient;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteVideo3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.view.entity.AliProofEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.viewmodel.self.website.WebsiteVideoModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;

import java.util.List;

import javax.inject.Inject;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class WebsiteVideoActivity3 extends AppActivity {

    private ActivityWebsiteVideo3Binding binding;

    private List<LocalMedia> locVideoList;
    //上传视频
    private VODUploadClient uploader;
    //上传凭证
    private AliProofEntity aliInfo;
    //视频
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;

    @Inject
    WebsiteVideoModel3 videoModel;

    public static void start(Context context){
        Intent intent = new Intent(context,WebsiteVideoActivity3.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_website_video3);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.rightView.setOnClickListener(this);
        binding.include.titleView.setText("企业视频");
        binding.include.rightView.setVisibility(View.GONE);
        binding.include.rightView.setText("重新上传");
        binding.setViewModel(videoModel);

        binding.videoUp.setOnClickListener(this);
    }

    @Override
    protected void init() {

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
        uploader = new VODUploadClientImpl(getApplicationContext());

        String playerUrl = getIntent().getStringExtra("playerUrl");
        String playerTime = getIntent().getStringExtra("playerTime");
        if(!TextUtils.isEmpty(playerUrl)){
        binding.rlVideo.setVisibility(View.VISIBLE);
        binding.include.rightView.setVisibility(View.VISIBLE);
        binding.videoUp.setVisibility(View.GONE);
        binding.videoView.setUp(playerUrl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
//        binding.videoView.startVideo();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.video_up:
            case R.id.right_view:
                PictureSelector.create(WebsiteVideoActivity3.this)
                        .openGallery(PictureMimeType.ofVideo())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .theme(R.style.picture_default_style)
                        .maxSelectNum(1)
                        .selectionMedia(locVideoList)
                        .forResult(PictureConfig.TYPE_VIDEO);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.TYPE_VIDEO) {
                binding.rlVideo.setVisibility(View.VISIBLE);
                binding.include.rightView.setVisibility(View.VISIBLE);
                binding.videoUp.setVisibility(View.GONE);
                locVideoList = PictureSelector.obtainMultipleResult(data);
                binding.videoView.setUp(locVideoList.get(0).getRealPath(), JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
                addFileToAli();
                videoModel.getVideoParams();
            }
        }
    }

    //添加文件
    private void addFileToAli() {
        VodInfo vodInfo = new VodInfo();
        vodInfo.setTitle("视频");
        vodInfo.setDesc("企业视频.");
        vodInfo.setCateId((int) System.currentTimeMillis());
        vodInfo.setTags(null);
        uploader.addFile(locVideoList.get(0).getRealPath(), vodInfo);
    }

    //阿里凭证
    public void setAliInfo(AliProofEntity aliInfo) {
        this.aliInfo = aliInfo;
        uploader.init(callback);
        uploader.start();
        DialogHelper.showProgressDialog(this, null, "视频上传中...", 0, false, null).setCanceledOnTouchOutside(false);
    }

    VODUploadCallback callback = new VODUploadCallback() {
        public void onUploadSucceed(UploadFileInfo info) {
            Log.e("onUploadSucceed", "onUploadSucceed");
            Intent intent = new Intent();
            intent.putExtra("videoId",aliInfo.getVideoId());
            setResult(RESULT_OK,intent);
            DialogHelper.dismissProgressDialog();
        }

        public void onUploadFailed(UploadFileInfo info, String code, String message) {
            Log.e("onUploadFailed", "onUploadFailed");
//            OSSLog.logError("onfailed ------------------ " + info.getFilePath() + " " + code + " " + message);
        }

        public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
            Log.e("onUploadFailed", "onUploadFailed");
//            OSSLog.logDebug("onProgress ------------------ " + info.getFilePath() + " " + uploadedSize + " " + totalSize);
        }

        public void onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired");
//            OSSLog.logError("onExpired ------------- ");
            // 重新刷新上传凭证:RefreshUploadVideo
//            uploadAuth = "此处需要设置重新刷新凭证之后的值";
            uploader.resumeWithAuth(aliInfo.getUploadAuth());
        }

        public void onUploadRetry(String code, String message) {
            Log.e("onUploadRetry", "onUploadRetry");
//            OSSLog.logError("onUploadRetry ------------- ");
        }

        public void onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume");
//            OSSLog.logError("onUploadRetryResume ------------- ");
        }

        public void onUploadStarted(UploadFileInfo uploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted");
//            OSSLog.logError("onUploadStarted ------------- ");
            uploader.setUploadAuthAndAddress(uploadFileInfo, aliInfo.getUploadAuth(), aliInfo.getUploadAddress());
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
}
